package com.jereh.topnews.demo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jereh.topnews.R;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ContextFileActivity extends AppCompatActivity {

    private EditText edit;
    private TextView content;
    private String fileName="test.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_context_file);
        edit=(EditText)findViewById(R.id.edit);
        content=(TextView)findViewById(R.id.content);
        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存内容
                if(saveData()) {
                    //把内容展示在content里
                    readData();
                }
            }
        });
    }

    /**
     * 读取数据
     */
    private void readData() {
        try {
            FileInputStream fis=openFileInput(fileName);
            byte[] b=new byte[fis.available()];
            fis.read(b);
            fis.close();
            content.setText(new String(b));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存文件
     * @return
     */
    private boolean saveData() {
        //在默认保存路径中创建一个文件
        try {
            FileOutputStream fos=openFileOutput(fileName,MODE_PRIVATE);
            //写入
            fos.write(edit.getText().toString().getBytes());
            fos.flush();
            fos.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
